package com.zscat.mallplus.dms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jpay.util.StringUtils;
import com.zscat.mallplus.dms.service.IQsgStoreService;
import com.zscat.mallplus.qsg.QsgStore;
import com.zscat.mallplus.utils.MeituanUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
public class MeituanTokenTask extends QuartzJobBean {

    @Autowired
    private IQsgStoreService storeService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        QueryWrapper qw = new QueryWrapper();
        qw.isNotNull("open_shop_uuid");
        List<QsgStore> stores = storeService.list(qw);
        for (QsgStore store : stores) {
            String meituanAppId = store.getMeituanAppid();
            String meituanAppSecret = store.getMeituanAppsecret();
            String meituanRefreshSession = store.getMeituanRefreshSession();
            if(StringUtils.isBlank(store.getMeituanRefreshSession())){
                log.info("店铺:{}未授权.",store.getName());
                continue;
            }
            if(StringUtils.isNotBlank(store.getMeituanRefreshSession()) && store.getRemainRefreshCount() == 0){
                log.info("店铺:{}刷新次数用完,请重新授权.",store.getName());
                continue;
            }
            try {
                String tokenContent = new MeituanUtil().refreshToken(meituanAppId, meituanAppSecret, meituanRefreshSession);
                JSONObject token = JSONObject.parseObject(tokenContent);
                log.info("美团token:{}", JSON.toJSONString(token));
                if (token.getIntValue("code") == 200) {
                    String session = token.getString("access_token");
                    String refreshToken = token.getString("refresh_token");
                    int remainRefreshCount = token.getIntValue("remain_refresh_count");
                    store.setMeituanSession(session);
                    store.setMeituanRefreshSession(refreshToken);
                    store.setRemainRefreshCount(remainRefreshCount);
                    store.setMeituanRefreshTime(new Date());
                    storeService.updateById(store);
                }
            } catch (IOException e) {
                log.error("获取美团token失败.异常:{}",e.getMessage());
            }
        }
    }
}
